//
//  SHTabBar.swift
//  三期微博1
//
//  Created by TownFish on 16/7/20.
//  Copyright © 2016年 TownFish. All rights reserved.
//

import UIKit
//声明协议

//使用weak修饰 需要继承NSObjectProtocol
protocol SHTabBarDelegate:NSObjectProtocol {
    //协议方法
    func composeButtonClick()
}


class SHTabBar: UITabBar {
    //声明代理
    weak var shDelegate:SHTabBarDelegate?
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //监听点击方法
    func buttonClick() {
        shDelegate?.composeButtonClick()
    }
    
    //MARK: - 设置视图
    private func setupUI() {
        addSubview(composeButton)
    }
    
    //设置子控件的frame
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置宽度
        let w = frame.width * 0.2
        //设置序号
        var index: CGFloat = 0
        //遍历子控件
        for value in subviews {
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
//                关闭控件值的打印
//                print(value)
                //设置UITabBarButton frame
                value.frame.origin.x = index * w
                value.frame.size.width = w
                
                //让序号每次都加
                index++
                //给中间的按钮设置两倍的间距(预留"添加"按钮位置)
                if index == 2 {
                    index++
                }
            }
        }
        
        
        //设置composeButton
        composeButton.center.x = frame.width * 0.5
        composeButton.center.y = frame.height * 0.5
    }
    
    
    
    //MARK: - 懒加载控件
    private lazy var composeButton: UIButton = {
        let  button = UIButton()
        //添加点击事件
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.sizeToFit()
        return button
    }()

}
